package com.czh.controller;

import com.czh.pojo.Book;
import com.czh.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.ArrayList;
import java.util.List;

//@Controller
@RequestMapping("/book")
public class BookController {
    private BookService bookService;

//    @Autowired
    public void setBookService(BookService bookService) {
        this.bookService = bookService;
    }

    @RequestMapping("/AllBook")
    public String getAllBook(Model model) {
        model.addAttribute("BookList", bookService.SelectAllBook());
        return "AllBook";
    }
//redirect和forward会使视图解析器的前后缀失效，所以要加完整地址
    @RequestMapping("/ToAddBook")
    public String AddPage() {
        return "AddBook";
    }

    @RequestMapping("/AddBook")
    public String AddBook(Book book){
        bookService.AddBook(book);
        return "redirect:/book/AllBook";
    }
    @RequestMapping("/ToUpdateBook")
    public String ToUpdate(@RequestParam("bookId") int bookId, Model model){
        model.addAttribute("book",bookService.SelectBookById(bookId));
        return "UpdateBook";
    }
    @RequestMapping("/UpdateBook")
    public String UpdateBook(Book book){
        bookService.UpdateBook(book);
        return "redirect:/book/AllBook";
    }
    @RequestMapping("/DeleteBook/{BookId}")
    public String DeleteBook(@PathVariable("BookId") int BookId){
        bookService.DeleteBook(BookId);
        return "redirect:/book/AllBook";
    }
    @RequestMapping("/SelectByName")
    public String SelectBookByName(@RequestParam("BookName") String BookName,Model model){
        List<Book> list = new ArrayList<Book>();
        Book book ;
        if (BookName != null && BookName.equals("")){
            list = bookService.SelectAllBook();
            model.addAttribute("error","输入为空!");
        } else if ((book = bookService.SelectBookByName(BookName))!=null) {
            list.add(book);
        } else {
            model.addAttribute("error","书籍不存在!");
        }
        model.addAttribute("BookList",list);
        return "AllBook";
    }
}
